from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKU, GoodsCategory, SPUSpecification
from meiduo_admin.serializers.skus import SKUSerializer, GoodsCategorySerializer,SPUSpecificationSerializer

from meiduo_admin.utils import PageNum


class SKUView(ModelViewSet):
    """
        sku表的增删改查
    """
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer
    pagination_class = PageNum
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword=self.request.query_params.get('keyword')
        if keyword is None or keyword=='':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)


    # 另外一种自定义路由的写法
    # 获取三级分类信息
    @action(methods=['get'],detail=False)
    def categories(self,request):
        # 1.查询分类表
        data=GoodsCategory.objects.filter(subs=None)
        # 2.返回分类信息
        ser=GoodsCategorySerializer(data,many=True)
        return Response(ser.data)

    # 获取规格信息
    def specs(self,request,pk):
        # 1.根据spu_id查询符合条件的规格信息
        data=SPUSpecification.objects.filter(spu_id=pk)
        # 2.序列化返回当前商品的规格信息
        ser=SPUSpecificationSerializer(data,many=True)
        return Response(ser.data)